import * as fs from 'fs'
import * as path from 'path'
import * as os from 'os'
import { URL } from 'url'
import axios from 'axios'

export const SEP = path.sep
export const EOL = os.EOL

export function ensureDirectoryExists(filePath: string) {
    const directory = path.dirname(filePath)
    if (!fs.existsSync(directory)) {
        fs.mkdirSync(directory, { recursive: true })
    }
}

export function emptyDir(path: string) {
    const files = fs.readdirSync(path)
    files.forEach(file => {
        const filePath = `${path}/${file}`
        try {
            // 使用 lstatSync 而不是 statSync，这样不会跟随软链接
            // 如果软链接指向的文件不存在，statSync 会抛出错误，但 lstatSync 不会
            const stats = fs.lstatSync(filePath)
            if (stats.isDirectory()) {
                emptyDir(filePath)
            } else {
                // 对于文件或软链接，直接删除
                fs.unlinkSync(filePath)
            }
        } catch (error: any) {
            // 如果 lstatSync 失败（例如权限问题），尝试直接删除
            // 这样可以处理一些边缘情况
            try {
                fs.unlinkSync(filePath)
            } catch (unlinkError) {
                // 如果删除也失败，记录错误但继续处理其他文件
                console.error(`Failed to delete ${filePath}:`, unlinkError)
            }
        }
    })
}

export function maskPassword(gitUrl: string):string{
    try {
        const parsedUrl = new URL(gitUrl);
        if (parsedUrl.username && parsedUrl.password) {
            parsedUrl.username = '******';
            parsedUrl.password = '******';
        }
        return parsedUrl.href;
    } catch (error) {
        return gitUrl;
    }
}

export function rmEmptyDir(path: string, level = 0) {
    const files = fs.readdirSync(path)
    if (files.length > 0) {
        let tempFile = 0
        files.forEach(file => {
            tempFile++
            rmEmptyDir(`${path}/${file}`, 1)
        })
        if (tempFile === files.length && level !== 0) {
            fs.rmdirSync(path)
        }
    } else {
        level !== 0 && fs.rmdirSync(path)
    }
}

/**
 * @param {*} path
 */
export function clearDir(path: string) {
    emptyDir(path)
    rmEmptyDir(path)
}

/**
 * @returns OSS endpoint
 */
export async function getEndpoint() {
    let endpoint =
        process.env['ENDPOINT'] || 'oss-cn-beijing-internal.aliyuncs.com'
    if (process.env['ENDPOINT'] != undefined) {
        return endpoint
    }
    let config = {
        method: 'get',
        url: 'oss-cn-beijing-internal.aliyuncs.com',
        timeout: 1000,
        headers: {}
    }
    await axios(config)
        .then(function (response: {data: any}) {
            endpoint = 'oss-cn-beijing-internal.aliyuncs.com'
        })
        .catch(function (err: any) {
            endpoint = 'oss-accelerate.aliyuncs.com'
        })
    return endpoint
}

// export async function ignoreGitSsl(workDir: string) {
//     // let platform: string = step.platform.getPlatform()
//     // if(platform != step.platform.PLATFORM_WIN){
//     //     let git = new GitTools()
//     //     await git.setEnvs(workDir, 'http.sslVerify', 'false');
//     // }
//     let git = new GitTools()
//     //step.info('ignore ssl command')
//     await git.setEnvs(workDir, 'http.sslVerify', 'false');
// }


export function masking(input: any): string {
    let inputString = `${input}`
    const regex = /([http|https]:\/\/[^:]+):[^:@]+(@.*)/;
    const replacedString = inputString.replace(regex, '$1$2');
    return replacedString;
}